import { PlusOutlined } from '@ant-design/icons';
import { Button, message } from 'antd';
import React, { useState, useRef } from 'react';
import { useIntl, FormattedMessage } from 'umi';
// import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { FormValueType } from './components/AddHostDrawerForm';
import AddHostDrawerForm from './components/AddHostDrawerForm';
import UpdateHostDrawerForm from './components/UpdateHostDrawerForm'
import { listHostsInfo, addHost, updateHost, removeHost } from '@/services/configserver/api';
import styles from './index.less';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAddHost = async (fields: API.HostsInfoListItem) => {
  const hide = message.loading('正在添加');
  try {
    await addHost({ ...fields });
    hide();
    message.success('添加成功');
    console.log('HostsInfoList Event=handleAddHost,value=', fields)
    return true;
  } catch (error) {
    hide();
    message.error('添加失败');
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdateHost = async (fields: FormValueType) => {
  const hide = message.loading('Configuring');
  try {
    await updateHost({
      // name: fields.hostname,
      // desc: fields.ip,
      // key: fields.id,
      // 如果是整个更新，应该是复制
      ...fields,
    });
    hide();

    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败,请重试');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param fileds
 */
const handleRemoveHost = async (fileds: API.HostsInfoListItem) => {
  const hide = message.loading('正在删除');
  console.log('HostsInfoList Event=handleRemoveHost,value=', fileds);

  try {
    await removeHost({
      id: fileds.id,
      hostname: fileds.hostname,
      arch: fileds.arch,
      ip: fileds.ip,
      os: fileds.os,
      password: fileds.password,
      username: fileds.username,
    });
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败');
    return false;
  };
}

// React.FC<>的在typescript使用的一个泛型，
// FC就是FunctionComponent的缩写，是函数组件，
// 我们使用React.FC来写 React 组件的时候，是不能用setState的，取而代之的是useState()、useEffect等 Hook API。
const HostInfoList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [addHostDrawerVisible, handleAddHostDrawerFormVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateHostDrawerVisible, handleUpdateHostDrawerFormVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.HostsInfoListItem>();

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<API.HostsInfoListItem>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.listHostsInfoTable.id"
          defaultMessage="ID"
        />
      ),
      dataIndex: 'id',
      tip: '数据库ID',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.listHostsInfoTable.hostname" defaultMessage="Hostname" />,
      dataIndex: 'hostname',
      sorter: true,
      valueType: 'textarea',
    },
    {
      title: <FormattedMessage id="pages.listHostsInfoTable.ip" defaultMessage="IP" />,
      dataIndex: 'ip',
      valueType: 'textarea',
    },
    {
      title: <FormattedMessage id="pages.listHostsInfoTable.username" defaultMessage="Username" />,
      dataIndex: 'username',
      valueType: 'textarea',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.listHostsInfoTable.password" defaultMessage="Password" />,
      dataIndex: 'password',
      valueType: 'textarea',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.listHostsInfoTable.os" defaultMessage="OS" />,
      dataIndex: 'os',
      valueType: 'textarea',
    },
    {
      title: <FormattedMessage id="pages.listHostsInfoTable.port" defaultMessage="PORT" />,
      dataIndex: 'port',
      valueType: 'textarea',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.listHostsInfoTable.titleStatus" defaultMessage="Status" />,
      dataIndex: 'os',
      hideInForm: true,
      valueEnum: {
        "Windows Server": {
          text: (
            <FormattedMessage
              id="pages.listHostsInfoTable.nameStatus.default"
              defaultMessage="Shut down"
            />
          ),
          status: 'Default',
        },
        "redhat": {
          text: (
            <FormattedMessage id="pages.listHostsInfoTable.nameStatus.processing" defaultMessage="Processing" />
          ),
          status: 'Processing',
        },
        "CentOS": {
          text: (
            <FormattedMessage id="pages.listHostsInfoTable.nameStatus.online" defaultMessage="Online" />
          ),
          status: 'Success',
        },
        default: {
          text: (
            <FormattedMessage
              id="pages.listHostsInfoTable.nameStatus.abnormal"
              defaultMessage="Abnormal"
            />
          ),
          status: 'Error',
        },
      },
    },
    {
      title: <FormattedMessage id="pages.listHostsInfoTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="update"
          onClick={() => {
            console.log("HostsInfoList 表单: Event=remove.onClick,value=", record);
            handleUpdateHostDrawerFormVisible(true);
            setCurrentRow(record);
          }}
        >
          <FormattedMessage id="pages.listHostsInfoTable.update" defaultMessage="Update" />
        </a>,
        <a
          key="remove"
          onClick={async () => {
            console.log("HostsInfoList 表单: Event=remove.onClick,value=", record);
            const success = await handleRemoveHost(record);
            if (success) {
              setCurrentRow(undefined);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          // onClick={() => {
          //   handleRemoveHost(record);
          //   setCurrentRow(record);
          // }}
          className={styles.listhostOperationRemove}
        >
          <FormattedMessage id="pages.listHostsInfoTable.remove" defaultMessage="Remove" />
        </a>,
      ],
    },
  ];

  return (
    // <PageContainer>
    <>
      <ProTable<API.HostsInfoListItem, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.listHostsInfoTable.title',
          defaultMessage: 'Enquiry form',
        })}
        actionRef={actionRef}
        // rowKey表示每一行的key
        rowKey="id"
        search={{
          // labelWidth: 60,
          span: 6,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleAddHostDrawerFormVisible(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.listHostsInfoTable.new" defaultMessage="New" />
          </Button>,
        ]}
        request={listHostsInfo}
        columns={columns}
      />
      {/* 添加主机 */}
      <AddHostDrawerForm
        onSubmit={async (value) => {
          console.log("AddHostDrawerForm 表单: Event=onSubmit,value =", value);
          const success = await handleAddHost(value);
          if (success) {
            handleAddHostDrawerFormVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}

        onClose={() => {
          console.log("AddHostDrawerForm 表单: Event=onClose");
          handleAddHostDrawerFormVisible(false);
        }}
        onVisibleChange={(visible) => {
          if (visible) {
            console.log("AddHostDrawerForm 表单: Event=onVisibleChange -> 显示AddHostForm");
          } else {
            console.log("AddHostDrawerForm 表单: Event=onVisibleChange -> 关闭AddHostForm");
          }
          handleAddHostDrawerFormVisible(visible);
        }}

        addHostDrawerVisible={addHostDrawerVisible}
      />
      {/* 更新主机信息 */}
      <UpdateHostDrawerForm
        onSubmit={async (value) => {
          console.log("UpdateHostDrawerForm 表单: Event=onSubmit,value =", value);
          const success = await handleUpdateHost(value);
          if (success) {
            handleUpdateHostDrawerFormVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}

        onClose={() => {
          console.log("UpdateHostDrawerForm 表单: Event=onClose");
          handleUpdateHostDrawerFormVisible(false);
          setCurrentRow(undefined);
        }}
        onVisibleChange={(visible) => {
          if (visible) {
            console.log("UpdateHostDrawerForm 表单: Event=onVisibleChange -> 显示UpdateHostDrawerForm");
          } else {
            console.log("UpdateHostDrawerForm 表单: Event=onVisibleChange -> 关闭UpdateHostDrawerForm");
          }
          //handleUpdateHostDrawerFormVisible(visible);
        }}

        updateHostDrawerVisible={updateHostDrawerVisible}

        values={currentRow || {}}
      />
    </>
    // </PageContainer>
  );
};

export default HostInfoList;
